import axios from 'axios';
import _ from 'lodash';
import dayjs from 'dayjs';
import * as  fs from 'fs';
import { compile, compileFromFile } from 'json-schema-to-typescript';
const url =
  "http://api-docs.tidoedu.com/api/open/plugin/export-full?type=json&pid=947&status=all&token=e064c12412b5b23539e467f0afde35f075382d7111dbba59dd3ae42f3a6a1063";

console.log('--->脚本运行:获取数据');
axios.get(url).then(async res => {
  // return;
  console.log('--->数据获取到,解析中...');
  const bodyStr = await Promise.all(res.data.map(groupCreateFn));
  const apiStr = `import request from './index';
    export const API = {${bodyStr.join(',')}
    };
     export default API;`;
  fs.writeFile('./api.ts', apiStr, () => {
    console.log('创建完成');
  });
});

const groupCreateFn = async item => {
  const bodyStr = await Promise.all((item.list || []).map(oneCreateFn));
  return `
          // ${item.name} 更新时间: ${dayjs.unix(item.up_time).format('YYYY-MM-DD hh:mm')}
          ${_.camelCase(item.desc) || item.name} : {
              ${bodyStr.join(',')}
              }`;
};

const oneCreateFn = async item2 => {
  let name = item2.path.replace(/\/v[\d.]+/, '').split('/');
  let body = saleRun(() => JSON.parse(item2.res_body).properties.body);
  let returnType = 'any';
  let returnNameType = _.capitalize(_.camelCase(name.join('_')));
  if (body && body.$$ref) {
    returnType = body.title = returnNameType;
    try {
      removeRefProperties(body);
      let interStr = (
        await compile(body, 'name', {
          unknownAny: false,
          bannerComment: ' ',
          additionalProperties: false,
        })
      )
        .replace(/\?:/g, ':')
        .replace(/export/g, 'declare');
      fs.writeFileSync(`./model/${returnNameType}.d.ts`, interStr);
    } catch (e) {
      console.log('--->52:', e);
      // console.log(JSON.stringify(body, null, 2));
      throw 1;
    }
  }
  return `
          // ${item2.title}  更新时间: ${dayjs.unix(item2.up_time).format('YYYY-MM-DD hh:mm')}
          ${name[name.length - 1]}(...args):Promise<${returnType}>{
            return request.${item2.method.toLowerCase()}('${item2.path}',...args)
            }`;
};

function saleRun(fn) {
  try {
    return fn();
  } catch (e) { }
}

function removeRefProperties(obj) {
  for (const key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      if ('$ref' in obj[key]) {
        delete obj[key]['$ref'];
      }
      removeRefProperties(obj[key]);
    }
  }
}
